<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Upload extends MX_Controller {
    protected $path_img_upload_folder;
    protected $path_img_thumb_upload_folder;
    protected $path_url_img_upload_folder;
    protected $path_url_img_thumb_upload_folder;

    private $_data = array();
    function __construct(){
        parent::__construct();
        $this->load->helper(array('form', 'url'));
        $this->load->library('ftp');
        /*$config['hostname'] = '192.168.1.101';
        $config['username'] = 'ftpuser';
        $config['password'] = '123456';
       // $config['port']     = 21;
        $config['passive']  = FALSE;
        $config['debug']    = TRUE;die(print_r($this->config->item('ftp_upload')));*/

        if($this->ftp->connect($this->config->item('ftp_upload'))){
          //  die(print 'connect sussessful');
        }
        else{
            //die(print 'not connect');
           // return;
        }
        
        //return ;
    }
    
    public function index(){
        $data = array();
        $this->template->add_css('assets/css/file_upload/jquery.fileupload.css');
        $this->template->add_css('assets/css/file_upload/jquery.fileupload-ui.css');
        $this->template->add_css('assets/css/file_upload/jquery.fileupload-noscript.css');
        $this->template->add_css('assets/css/file_upload/jquery.fileupload-ui-noscript.css');
        
        $this->template->add_js('assets/scripts/file_upload/vendor/jquery.ui.widget.js');
        $this->template->add_js('assets/scripts/file_upload/load-image.min.js');
        $this->template->add_js('assets/scripts/file_upload/jquery.iframe-transport.js');
        $this->template->add_js('assets/scripts/file_upload/jquery.fileupload.js');
        $this->template->add_js('assets/scripts/file_upload/jquery.fileupload-process.js');
        $this->template->add_js('assets/scripts/file_upload/jquery.fileupload-image.js');
        $this->template->add_js('assets/scripts/file_upload/jquery.fileupload-angular.js');
        $this->template->add_js('assets/scripts/file_upload/app.js');
        $this->template->parse_view('content' , 'upload/index', $data);
        $this->template->render();    
    }
    
    public function image(){
        $this->load->library('UploadHandler');	
        $upload_handler = new UploadHandler();
        die(print_r($upload_handler));
    }
    
    public function do_upload() {         
        $upload_path_url = base_url() . 'files/';

        //$config['upload_path'] = FCPATH . 'uploads/';
        $config['upload_path'] = FCPATH . 'files/';
        $config['allowed_types'] = 'jpg|jpeg|png|gif';
        $config['overwrite'] = TRUE;
        $config['max_size'] = '30000';      
        $this->load->library('upload', $config); 
        
        if (!$this->upload->do_upload('files')) { 
            //$error = array('error' => $this->upload->display_errors());
            //$this->load->view('upload', $error);

            //Load the list of existing files in the upload directory
            $existingFiles = get_dir_file_info($config['upload_path']);
            $foundFiles = array();
            $f=0;
            foreach ($existingFiles as $fileName => $info) {
              if($fileName!='thumbs'){//Skip over thumbs directory
                //set the data for the json array   
                $foundFiles[$f]['name'] = $fileName;
                $foundFiles[$f]['size'] = $info['size'];
                $foundFiles[$f]['url'] = $upload_path_url . $fileName;
                $foundFiles[$f]['thumbnailUrl'] = $upload_path_url . 'thumbs/' . $fileName;
                $foundFiles[$f]['deleteUrl'] = base_url() . 'upload/deleteImage/' . $fileName;
                $foundFiles[$f]['deleteType'] = 'DELETE';
                $foundFiles[$f]['error'] = null;

                $f++;
              }
            }
            $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(array('files' => $foundFiles)));
        } 
        else { 
            
            $data = $this->upload->data();  
            
            // to re-size for thumbnail images un-comment and set path here and in json array
            $config = array();
            $config['image_library'] = 'gd2';
            $config['source_image'] = $data['full_path'];
            $config['create_thumb'] = TRUE;
            $config['new_image'] = $data['file_path'] . 'thumbs/';
            $config['maintain_ratio'] = TRUE;
            $config['thumb_marker'] = '';
            $config['width'] = 75;
            $config['height'] = 50;
            $this->load->library('image_lib', $config);
            $this->image_lib->resize();
            
            //set the data for the json array   
            $info->name = $data['file_name'];
            $info->size = $data['file_size'];
            $info->type = $data['file_type'];
            $info->url = $upload_path_url . $data['file_name'];
            // I set this to original file since I did not create thumbs.  change to thumbnail directory if you do = $upload_path_url .'/thumbs' .$data['file_name']
            $info->thumbnailUrl = $upload_path_url . 'thumbs/' . $data['file_name'];
            $info->deleteUrl = base_url() . 'upload/deleteImage/' . $data['file_name'];
            $info->deleteType = 'DELETE';
            $info->error = null;

            $files[] = $info; 
            //this is why we put this in the constants to pass only json data
            if (IS_AJAX) {
                echo json_encode(array("files" => $files));
                //this has to be the only data returned or you will get an error.
                //if you don't give this a json array it will give you a Empty file upload result error
                //it you set this without the if(IS_AJAX)...else... you get ERROR:TRUE (my experience anyway)
                // so that this will still work if javascript is not enabled
            } else {
                $file_data['upload_data'] = $this->upload->data();
                $this->load->view('upload/upload_success', $file_data);
            }
        }
    }
    
    public function ftp_upload(){
        $upload_path_url = '/home/ftpuser/files/';

        //$config['upload_path'] = FCPATH . 'uploads/';
        $config['upload_path'] = $upload_path_url;// . 'files/';
        $config['allowed_types'] = 'jpg|jpeg|png|gif';
        $config['overwrite'] = TRUE;
        $config['max_size'] = '30000';
        
       
        $this->load->library('upload', $config); 
        
        //$this->ftp->upload($_FILES['files']['tmp_name'], $upload_path_url . $_FILES['files']['name'], "ascii", 0775);
        if(!$this->ftp->upload($_FILES['files']['tmp_name'] , $upload_path_url . $_FILES['files']['name'] , null , 0775)){
        
        }
        else{            
            //die(print_r($_FILES['files']));
            $data = $_FILES['files'];//$this->upload->data();             
            // to re-size for thumbnail images un-comment and set path here and in json array
            $config = array();
            $config['image_library'] = 'gd2';
            $config['source_image'] = $upload_path_url . $_FILES['files']['name'];//$data['full_path'];
            $config['create_thumb'] = TRUE;
            $config['new_image'] = $upload_path_url . 'thumbs/';//$data['file_path'] . 'thumbs/';
            $config['maintain_ratio'] = TRUE;
            $config['thumb_marker'] = '';
            $config['width'] = 75;
            $config['height'] = 50;//die(print_r($config));
            $this->load->library('image_lib', $config);
            $this->image_lib->resize();
            
            //set the data for the json array   
            $info->name = $data['name'];
            $info->size = $data['size'];
            $info->type = $data['type'];
            $info->url = $upload_path_url . $data['name'];
            // I set this to original file since I did not create thumbs.  change to thumbnail directory if you do = $upload_path_url .'/thumbs' .$data['file_name']
            $info->thumbnailUrl = 'file:///' . $upload_path_url . 'thumbs/' . $data['name'];
            $info->deleteUrl = base_url() . 'upload/deleteImage/' . $data['name'];
            $info->deleteType = 'DELETE';
            $info->error = null;

            $files[] = $info; 
            //this is why we put this in the constants to pass only json data
            if (IS_AJAX) {
                echo json_encode(array("files" => $files));
                //this has to be the only data returned or you will get an error.
                //if you don't give this a json array it will give you a Empty file upload result error
                //it you set this without the if(IS_AJAX)...else... you get ERROR:TRUE (my experience anyway)
                // so that this will still work if javascript is not enabled
            } else {
                $file_data['upload_data'] = $this->upload->data();
                $this->load->view('upload/upload_success', $file_data);
            }
        }

        $this->ftp->close();
        return ;      
    }
    
    public function deleteImage($file) {//gets the job done but you might want to add error checking and security
        $success = unlink(FCPATH . 'uploads/' . $file);
        $success = unlink(FCPATH . 'uploads/thumbs/' . $file);
        //info to see if it is doing what it is supposed to 
        $info->sucess = $success;
        $info->path = base_url() . 'uploads/' . $file;
        $info->file = is_file(FCPATH . 'uploads/' . $file);

        if (IS_AJAX) {
            //I don't think it matters if this is set but good for error checking in the console/firebug
            echo json_encode(array($info));
        } else {
            //here you will need to decide what you want to show for a successful delete        
            $file_data['delete_data'] = $file;
            $this->load->view('admin/delete_success', $file_data);
        }
    }

}